//
//  glesView.m
//  myfistopengl
//
//  Created by huiti123 on 2017/3/30.
//  Copyright © 2017年 wtw. All rights reserved.
//

#import "glesView.h"
#import <OpenGLES/ES2/gl.h>



@interface glesView()

@property (strong, nonatomic) CAEAGLLayer *eaglLayer;


@end




@implementation glesView{

    
}


+(Class) layerClass {
    return [CAEAGLLayer class];
}


-(instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        
        [self setupLayer];
        [self setupContext];
    
        
    }
    
    return  self;
}


-(void) render{
    if(_context == nil) return;
    

}
-(void) setupLayer {
    
    _eaglLayer = (CAEAGLLayer *)self.layer;
    
    _eaglLayer.opaque = YES;
    
    // draw rgba 8 的 颜色格式.
    _eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
}


-(void) setupContext{
    EAGLRenderingAPI api = kEAGLRenderingAPIOpenGLES2;
    
    _context = [[EAGLContext alloc]initWithAPI:api];
    if(!_context){
        NSLog(@"failed to ininitialize opengles 2.0 context");
    }
    
    BOOL ret  = [EAGLContext setCurrentContext:_context];
    if(!ret){
        _context = nil;
        NSLog(@"failed to set current context");
        exit(0);
    }
    
}

// color buffer.
-(void) setupBuffer{
    glGenRenderbuffers(1, &_renderBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, _renderBuffer);
    
    [_context renderbufferStorage:GL_RENDERBUFFER fromDrawable:_eaglLayer];
    
    glGenFramebuffers(1, &_frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, _frameBuffer);
    
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, _renderBuffer);
}

-(void) destoryBuffer{
    
    glDeleteRenderbuffers(1, &_renderBuffer);
    _renderBuffer = 0;
    
    glDeleteBuffers(1, &_frameBuffer);
    _frameBuffer = 0;
    
}

-(void) layoutSubviews{
    [EAGLContext setCurrentContext:_context];
    
    [self destoryBuffer];
    [self setupBuffer];
    
}
@end
